<?php class Sell_out extends CI_Controller {
	
  public function __construct() {
    parent::__construct();
    $this->load->library('session');
    $this->load->library('form_validation');
    $this->load->library('encrypt');
    $this->load->library('fpdf');
    $this->load->library('enc');
    $this->load->model('mmaster');
    $this->load->model('mglobal');
    $this->load->model('msell_out');
    $this->is_logged_in();
    $this->load->helper('url');
  }
	
	//cek login
	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}		
	}
	
	function index($lastid="")
	{
		$data['lastId'] 	= $lastid;	   
		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-sell-out';
		$this->load->view($data['template'],$data);
	}
	
	//ambil list data untuk jenis pembayaran
	public function termin() {
		$termin = $this->msell_out->termins();
		return $termin;
	}
	
  function getOutletList(){
    $user_group_id = $this->input->post("user_group_id");
    $user_id       = $this->input->post("sales_id");
    $data = $this->msell_out->get_outlet_list($user_group_id, $user_id); //Search DB
    echo json_encode($data);
  }
    
  //fungsi untuk membuat sell out baru
  function newsell_out( )
  {
    $data['template']  = "shell/smooth";
    $data['main_view'] = "trans/sell_out_create";
    
    $cluster_id        = $this->mglobal->user_cluster($this->session->userdata('username'));
    $data['salesID']   = $this->msell_out->get_sales_team($cluster_id, array(31, 35, 36) );

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region'] = $teritori[0];
    $data['cluster'] = $teritori[1];

    ## INITIATE SAVE SELL OUT TRANSACTIONS #########################################################
    $channel_id = $this->input->post('partner_id');
    $sell_date  = $this->input->post('sell_out_date');
    $sales_id   = explode('_', $this->input->post('sales_id'));
    $remark     = $this->input->post('remark');
    $iccid      = $this->input->post('iccid');

    $this->form_validation->set_rules('sell_out_date', 'Tanggal Sell Out', 'required');
    $this->form_validation->set_rules('partner_id',    'Nama Partner',     'required');
    $this->form_validation->set_rules('sales_id',      'Nama Sales',       'required');
    $this->form_validation->set_rules('iccid[]',       'Item/ICCID',       'required');

    $dup_iccid = array(); $new_iccid = array();

    if ($this->form_validation->run() != false) {
      $duplicate_iccid = array_count_values($iccid);    // Returns ['iccid_0']=>counts, [iccid_1]=>counts
      $unique_iccid    = array_unique($iccid);             // Returns [0]=>"iccid_0", [1]=>"iccid_1"
      $duplicate_iccid; 
      $unique_iccid; 
      foreach ($unique_iccid as $key) {   // $key become unique_iccid value: iccid_0, iccid_1
        if($duplicate_iccid[$key] == 1) 
          { $new_iccid[] = $key; }        // if the count equal to 1, create new array, the array is now unique
        else 
          { $dup_iccid[] = $key; }        // if the count greater then to 1, create new array contains unique iccid above.
      }

      $iccidsama='';
      foreach ($dup_iccid as $a)
        { $iccidsama .= $a.', '; }
      // Validate each unique iccids and return as new array named valid_iccid
      $i = 0;
      foreach ($new_iccid as $key) { 
        $valid_iccid[] = $this->_validate_item($key); 
        if ($valid_iccid[$i] == null)
          { unset($valid_iccid[$i]) ;}
        $i++;
      }

      if (count($valid_iccid) != 0 ) {  // if array is not null, save transactions
        $this->db->trans_begin();

        $sell_out_id = $this->msell_out->save_sell_out($sales_id[1], $channel_id, $sell_date, $remark);
        $this->msell_out->save_sell_out_detail($sell_out_id, $valid_iccid); 

        if ($this->db->trans_status() === FALSE)
        {
          $this->db->trans_rollback();
           $this->session->set_flashdata('message', 'Tidak ada item yang valid');
        }
        else
        {
          $this->db->trans_commit();
          
          if (count($dup_iccid) != 0) { $message = "Data berhasil disimpan dengan nomor transaksi $sell_in_id, terdapat duplikat ICCID: $iccidsama" ; }
          else {$message = "Data berhasil disimpan dengan nomor transaksi $sell_out_id" ; }
          $this->session->set_flashdata('message', $message);
          redirect(base_url().'index.php/sell_out');
        }
      }
    } // end of form_validation
    else {
      if ($teritori[1]) 
        { $this->load->view($data['template'], $data, FALSE); }
      else
        { redirect("index.php/cluster"); }
    }
    ################################################################################################

	}
	
  public function _validate_item($iccid)
  {
    $item = $this->msell_out->validate_item($iccid);
    return $item;
  }
    
  function getItemList() {
    $channel_id = $this->input->post('channel_id');
    $data = $this->msell_out->getItems($channel_id);
    echo json_encode($data);
  }

      // untuk manage data yang ditampilkan pada grid view
    public function read() {
		//echo json_encode( $this->msell_out->getAllSellin() );
		$result = $this->msell_out->getAllSellin();
    // print_r($result);die();

       // encode
        for($i=0;$i<count($result['aaData']);$i++){
    		$result['aaData'][$i][1] = $this->enc->fogit($result['aaData'][$i][1]);
    	}
        
        //penambahan nomor statis untuk grid SSP
        $start=$_GET['iDisplayStart'];
        $result['iDisplayStart']=$start;

        echo json_encode($result);
        // print_r(json_encode($result));die();
	}
    
    function defoger()
    {
        $result = $this->enc->defog($this->input->post('str'));
        echo $result;  
    }
    
        
    //proses data untuk halaman detail
	function getDetail($id1='', $id2='')
	{
		//$sell_id = $id1;
		$sell_id = $this->enc->defog($id1); 
		
		$temp = $this->msell_out->getById($sell_id);
		$sales_id = $temp->sales_id;
		
        
        $temp = "";
		$temp = $this->msell_out->getClusterName($this->session->userdata('username'));
		$data['ter_name'] 	= $temp[0]['territory_name'];
		$ter_id 			= $temp[0]['territory_id'];

		
		$list = $this->pdfAndDetail($sell_id);

		$data['sellout'] = $list[2];
		$data['sales_name'] = $list[3];
		$data['sellout_detail'] = $list[4];		
		//$data['outlet_name'] = $data['sell_in']->channel_id;
		$data['outlet_name'] = $this->msell_out->getPartner($data['sellout']->territory_id);
		
		


		for($ii=0;$ii<count($list[4]);$ii++)	
		{
			$data['itemDetail'][$ii] = $list[5+$ii];
			$data['detailCounter'] = $ii + 1;
		}
		
		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-sell-out-detail';
		$this->load->view($data['template'],$data);
		
	
	}
    
    
   	function pdfAndDetail($sell_id)
	{
		$list = array();
		
		//$list[0] = $this->concateId($sell_id);
		
		
		$list[2] = $this->msell_out->getById($sell_id);				
		$list[3] = $this->msell_out->getNikName($list[2]->sales_id);		
		
		$this->db->select('*');
		$this->db->where('sellout_id', $sell_id);
		$q = $this->db->get('t_trx_sellout_detail');
		$list[4] = $q->result_array();
		
		for($ii=0;$ii<count($list[4]);$ii++)
		{
			$list[$ii+5] = $this->msell_out->getItemDetail($list[4][$ii]['iccid']);
		}
			
		return $list;
	
	}
    
    
    

}
